const router = require('koa-router')()
const { query } = require('./../config/dbPool');
const {
    QUERY_Food_dim_SQL,
    QUERY_SQL,
    INSERT_SQL,
    UPDATE_SQL,
    DELETE_SQL,
    QUERY_Food_step_SQL,
    INSERT_FoodSQL,
    DELETE_Same_SQL,
    INSERT_FoodStepSQL,
    DELETE_Same_steps_SQL,
    QUERY_Food_SQL,
    QUERY_Food_Kind_SQL,
    INSERT_Food_Upload,
    QUERY_Food_material_SQL,
    INSERT_Food_step_Upload,
    QUERY_Food_SQL_ID,
    QUERY_SQL_By_Count_All,
    INSERT_Community_Upload
    
} = require('./../config/dbSQL');
const data = require('./../config/datapull');
const fs = require('fs');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const { title } = require('process');
const jwt = require('jsonwebtoken')
const secret = 'test'
//查询用户
router.get('/search', async ctx => {
    const data = await query(QUERY_SQL);
    ctx.body = {
        data,
    };
});
//通过菜谱名字模糊查询
router.get('/searchDimFood', async ctx => {
    // let string=ctx.query.title
    // console.log(string.slice(1,-1))
    // console.log(ctx.query.title)
    const data = await query(QUERY_Food_dim_SQL, `%` + ctx.query.title + `%`);
    ctx.body = {
        data,
    };

});
//通过分类模糊查询
router.get('/searchKindDimFood', async ctx => {
    // console.log(ctx.query.title)

    const data = await query(QUERY_Food_Kind_SQL, `%` + ctx.query.kind + `%`);
    console.log(data)
    ctx.body = {
        data,
    };
});

//查询菜谱步骤
router.get('/searchFood', async ctx => {

    const data = await query(QUERY_Food_step_SQL, ctx.query.id).then(res => {
        const stepData = res.results
        // console.log(stepData)
        ctx.body = {
            stepData
        };
    })


});
//根据原材料智能组菜
router.get('/searchMaterial', async ctx => {

    const parts = ctx.query.material.split(',', 3);
    const values = [
        '%' + parts[0] + '%',
        '%' + parts[1] + '%',
        '%' + parts[2] + '%'
    ];
    const material = await query(QUERY_Food_material_SQL, values)
    ctx.body = {
        material
    }
})



// 插入用户
router.post('/save', async ctx => {
    const res = ctx.request.body;
    console.log(ctx.query.data)
    // const { username = ctx.query.data.username, count = ctx.query.data.count, password = ctx.query.data.password } = res;
    // if (username && count) {
    //     const queryData = {
    //         username,
    //         count,
    //         password,
    //     };
    //     const data = await query(INSERT_SQL, queryData);
    //     if (data && data.status && data.status === 200) {
    //         ctx.body = {
    //             status: 200,
    //             msg: "操作成功",
    //         };
    //     } else {
    //         ctx.body = data;
    //     }
    // }
});

// //插入菜谱数据
// router.post('/saveFood', async ctx => {
//     var arr = []
//     // ctx.body=data.searchFood("蛋炒饭",1)
//     data.getTodayFood().then(result => {

//         let rl = result.length
//         console.log(result)
//         for (let i = 0; i < rl; i++) {
//             result[i].foodList.forEach(e => {
//                 arr.push(e.href)

//             })

//             // data.foodDetail(arr[i]).then(data1 => {

//             //     const res = ctx.request.body;
//             //     const { title = data1.title, coverImage = data1.coverImage, finishImages = data1.finishImages } = res;
//             //     if (title && coverImage) {
//             //         const queryData = {
//             //             title,
//             //             coverImage,
//             //             finishImages,
//             //         };
//             //         const data = query(INSERT_FoodSQL, queryData);
//             //         if (data && data.status && data.status === 200) {
//             //             ctx.body = {
//             //                 status: 200,
//             //                 msg: "操作成功",
//             //             };
//             //         } else {
//             //             ctx.body = data;
//             //         }
//             //     }

//             // })
//         }
//     })
//     // const res = ctx.request.body;
//     // const { username = '', count = '', password = '' } = res;
//     // if (username && count) {
//     //     const queryData = {
//     //         username,
//     //         count,
//     //         password,
//     //     };
//     //     const data = await query(INSERT_SQL, queryData);
//     //     if (data && data.status && data.status === 200) {
//     //         ctx.body = {
//     //             status: 200,
//     //             msg: "操作成功",
//     //         };
//     //     } else {
//     //         ctx.body = data;
//     //     }
//     // }
// });

//详细插入菜谱数据
router.post('/saveDetailFood', async ctx => {

    var arr1 = []
    data.searchFood("水果", 5).then(result => {
        console.log(result.foodList)
        let rl = result.foodList.length


        // result.foodList.forEach(e => {
        //     arr1.push(e.href)

        // })

        // for (let i = 0; i < rl; i++) {
        //     data.foodDetail(arr1[i]).then(data1 => {


        //         const res = ctx.request.body;
        //         const {
        //             href = arr1[i],
        //             title = data1.title,
        //             coverImage = data1.coverImage,
        //             finishImages = data1.finishImages[0],
        //             main_material = data1.neetFoods[0].needList.toString(),
        //             excipient = data1.neetFoods[1].needList.toString(),
        //             kind = "水果类"
        //         } = res;
        //         if (title && coverImage) {
        //             const queryData = {
        //                 href,
        //                 title,
        //                 coverImage,
        //                 finishImages,
        //                 main_material,
        //                 excipient,
        //                 kind,
        //             };

        //             const data = query(INSERT_FoodSQL, queryData);
        //             if (data && data.status && data.status === 200) {
        //                 ctx.body = {
        //                     status: 200,
        //                     msg: "操作成功",
        //                 };
        //             } else {
        //                 ctx.body = data;
        //             }
        //         }

        //     })
        // }
    })

});


router.post('/saveFoodStep', async ctx => {

    // const data0 = await query(QUERY_Food_SQL, `%` + '水产' + `%`);
    const data0 = await query(QUERY_Food_Kind_SQL, `%` + '水果类' + `%`);
    data0.results.forEach(e => {
        data.foodDetail(e.href).then(data1 => {
            const res = ctx.request.body;
            data1.steps.forEach((item, index) => {
                const {
                    stepName = data1.title + `步骤` + item.stepNum,
                    stepNum = item.stepNum,
                    stepImage = item.stepImage,
                    stepDescribe = item.stepDescribe,
                    food_id = e.food_id
                } = res;
                if (stepNum && stepImage) {
                    const queryData = {
                        stepName,
                        stepNum,
                        stepImage,
                        stepDescribe,
                        food_id
                    };

                    const data = query(INSERT_FoodStepSQL, queryData);
                    if (data && data.status && data.status === 200) {
                        ctx.body = {
                            status: 200,
                            msg: "操作成功",
                        };
                    } else {
                        ctx.body = data;
                    }
                }

            })


        })

    })

});



//更新
router.post('/update', async ctx => {
    const res = ctx.request.body;
    const { username = '', id = 1 } = res;
    if (username && id) {
        const queryData = [username, id];
        const data = await query(UPDATE_SQL, queryData);
        if (data && data.status && data.status === 200) {
            ctx.body = {
                status: 200,
                msg: "操作成功",
            };
        } else {
            ctx.body = data;
        }
    }
});


//菜谱查重
router.del('/deleteSame', async ctx => {
    const res = ctx.request.body;

    const { title = '蛋炒饭' } = res;
    if (title) {
        const queryData = [title];
        const data = await query(DELETE_Same_SQL, queryData);
        // const data = await query(DELETE_Same_steps_SQL, queryData);
        if (data && data.status && data.status === 200) {
            ctx.body = {
                status: 200,
                msg: "操作成功",
            };
        } else {
            ctx.body = data;
        }
    }
});


//根据主键id 删除
router.del('/delete', async ctx => {
    const res = ctx.request.body;
    const { id } = res;
    if (id) {
        const queryData = [id];
        const data = await query(DELETE_SQL, queryData);
        if (data && data.status && data.status === 200) {
            ctx.body = {
                status: 200,
                msg: "操作成功",
            };
        } else {
            ctx.body = data;
        }
    }
});

//菜谱上传接口
// 使用koa-body中间件解析表单数据
router.post('/foodUpload', async ctx => {
    //从token获取用户信息
    const count = jwt.verify(ctx.headers.authorization.split(' ')[1], secret).name
    const u_info = await query(QUERY_SQL_By_Count_All, count)
    const user_name = u_info.results[0].username
    const user_img = u_info.results[0].user_img
    const uid = u_info.results[0].uid;
    //从请求中获取菜谱信息和图片
    const { title, coverImage, materialName, materialNum, excipientName, excipientNum, story, stepimg, step } = ctx.request.body;
    const material_ctx = materialName.map((element, index) => {
        return element + materialNum[index];
    });
    const excipient_ctx = excipientName.map((element, index) => {
        return element + excipientNum[index];
    });
    const main_material = material_ctx.join(',')
    const excipient = excipient_ctx.join(',')


    function saveBase64Image(base64String, filePath) {
        const base64Data = base64String.replace(/^data:image\/\w+;base64,/, '');
        const buffer = Buffer.from(base64Data, 'base64');
        fs.writeFileSync(filePath, buffer);
    }

    function getImageUrl(filename) {
        const baseUrl = 'http://8.130.72.2:3000/images/'; // 替换为你的图片服务器 URL
        return `${baseUrl}${filename}`;
    }

    const base64Image =coverImage; // 替换为你的 base64 图片字符串
   
    // const imageName = 'image.png'; // 替换为你想要的图片文件名
    const imageName = uuidv4()+'.png'
    const dir=path.resolve(__dirname, '..')
    const filePath = path.join(dir, 'public', 'images', imageName);

    saveBase64Image(base64Image, filePath);

    const imageUrl = getImageUrl(imageName);

    // console.log('Image URL:', imageUrl);



    // 将菜谱信息和图片文件名存储到菜谱表中
    const params = [title, imageUrl, main_material, excipient];
    await query(INSERT_Food_Upload, params).then(res => {
        ctx.body = {
            success: true,
            message: '菜谱上传成功',
        };
    });
    const id_data = await query(QUERY_Food_SQL_ID, title)
    const food_id = id_data.results[0].food_id
    //将上传内容到社区表
    const imageName1 = uuidv4()+'.png'
    saveBase64Image(stepimg, filePath);
    const stepImage = getImageUrl(imageName1);
    const stepName = title + "步骤1";
    const params0=[uid,title, imageUrl, main_material, excipient,user_img,user_name,stepImage,stepName,food_id];
    await query(INSERT_Community_Upload, params0).then(res => {
        ctx.body = {
            success: true,
            message: '社区上传成功',
        };
    });

    //将菜谱信息和图片文件名存储到菜谱步骤表
    if (Array.isArray(step) && Array.isArray(stepimg)) {
        //多个步骤
        step.forEach(ctx, index => {
            const stepName = title + "步骤" + index;
            const stepNum = index

            const stepDescribe = ctx
            const params1 = [stepName, stepNum, stepImage, stepDescribe, food_id]
            query(INSERT_Food_step_Upload, params1).then(res => {
                ctx.body = {
                    success: true,
                    message: '菜谱步骤上传成功',
                }
            })
        })

    } else {
        const stepName = title + "步骤1"
        const stepNum = 1
        const stepDescribe = step
        const params1 = [stepName, stepNum, stepImage, stepDescribe, food_id]
        await query(INSERT_Food_step_Upload, params1).then(res => {
            ctx.body = {
                success: true,
                message: '菜谱步骤上传成功',
            }
        })
    }
});

module.exports = router;